package com.ba360.portal.util;

import java.util.Properties;

import org.quartz.CronExpression;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;

/**
 * 
 * 
 */
public class AutoNotifyScheduler {
	
	private static AutoNotifyScheduler instance;

	private static Scheduler scheduler;
	
	private boolean status;
	
	private AutoNotifyScheduler() {
		status = false;
	}

	public static AutoNotifyScheduler getInstance() {
		
		if (null == instance) {
			
			synchronized (AutoNotifyScheduler.class) {
				
				instance = new AutoNotifyScheduler();
			}
		}
		return instance;
	}
	 
	public void executeCronJob() throws Exception {
		
		// Initiate a Schedule Factory
		SchedulerFactory schedulerFactory = new StdSchedulerFactory();
		// Retrieve a scheduler from schedule factory
		scheduler = schedulerFactory.getScheduler();
		
		// current time
		long ctime = System.currentTimeMillis();
		
		// Initiate JobDetail with job name, job group, and executable job
		// class
		JobDetail jobDetail = new JobDetail("jobDetail2", "jobDetailGroup2", AutoNotifyJob.class);
		// Initiate CronTrigger with its name and group name
		CronTrigger cronTrigger = new CronTrigger("cronTrigger", "triggerGroup2");
		try {
			// setup CronExpression
			Log.info(String.valueOf(ctime));
			CronExpression cexp = new CronExpression("2 * * * * ?");
			// Assign the CronExpression to CronTrigger
			cronTrigger.setCronExpression(cexp);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		// schedule a job with JobDetail and Trigger
		scheduler.scheduleJob(jobDetail, cronTrigger);
		
		// start the scheduler
		scheduler.start();
		
		status = true;
	}
	
	protected void finalize() throws Throwable {
		
		Properties prop = new Properties();
		String firstname = "Vivek";
		prop.setProperty("Fullname", firstname);
		prop.setProperty("ToEmailAddr", "writetofredy@gmail.com");
		prop.setProperty("FromEmailAddr", "response@bangalore360.com");
		prop.setProperty("Subject", "Auto Notification Email");
		prop.setProperty("Body", "Scheduler stopped by some resource" + "<br>\n");
		
		try {
			EmailSender.sendEmail(EmailSender.TYPE_AUTONOTIFY, prop);
		} catch (Exception e) {
			
			System.out.println(e);
			Log.error(e.toString());
		} finally {
			super.finalize();
		}
	}

	public void shutdown() throws Exception {
		
		scheduler.shutdown(true);
		status = false;
	}

	public boolean getStatus() {
		return status;
	}

	public void setStatus(boolean status) {
		this.status = status;
	}
	
	public static void main(String args[]) throws Exception {
		Log.init(null);
		AutoNotifyScheduler notifyScheduler = AutoNotifyScheduler.getInstance();
		notifyScheduler.executeCronJob();
	}
}